<?php

namespace App\Http\Controllers\Admin;

use App\Models\Manage;
use App\Models\StudyRoomReservationRemoteOperation;
use Illuminate\Support\Facades\DB;

/**
 * 书房预约远程操作类
 */
class StudyRoomReservationRemoteOperationController extends CommonController
{

    protected $model;

    public function __construct()
    {
        parent::__construct();

        $this->model = new StudyRoomReservationRemoteOperation();
    }

    /**
     *  列表
     *  @param page int 当前页数
     *  @param limit int 分页大小
     *  @param reservation_id 门禁id
     *  @param type 类型  1 远程开门   6 下载白名单； 7 清空本地所有白名单；
     *  @param status 类型  状态   1 已成功 2 处理中 3待处理 
     *  @param start_time int 开始时间
     *  @param end_time int 结束时间
     *  @param keywords string 搜索筛选
     */
    public function lists()
    {
        $reservation_id = $this->request->reservation_id;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;
        $type = $this->request->type;
        $status = $this->request->status;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;

        $res = $this->model->lists(null, $reservation_id, $keywords, $type, $status, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }

        foreach ($res['data'] as $key => $val) {
            //获取管理员名称
            $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", true, $res);
    }


    /**
     * 远程操作
     * @parma type 类型  1 远程开门   6 下载白名单； 7 清空本地所有白名单；
     * @parma ids 预约id  远程开柜时必须存在 all  表示所有  多个逗号拼接 
     */
    public function remoteOperation()
    {
        $ids = $this->request->ids;
        $type = $this->request->type;
        if (empty($type) || empty($ids)) {
            return $this->returnApi(201, "参数错误");
        }
        if ($type == 1 && (empty($ids) || $ids == 'all')) {
            return $this->returnApi(201, "远程开门必须选择设备");
        }
        // 启动事务
        DB::beginTransaction();
        try {
            $result = $this->model->add($ids, $type);
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "操作成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
